Page({
  data: {
    userInfo: {
      configurationId: 0,
      colorImg: '',
      name: '',
      phone: '',
      address: [],
    },
    region: ['省份', '城市', '区'],
    isFormComplete: false,
  },

  onLoad(options) {
    this.setData({
      'userInfo.configurationId': options.carId,
      'userInfo.colorImg': options.imageUrl,
    });
  },

  onRegionChange(e) {
    this.setData({
      region: e.detail.value,
      'userInfo.address': e.detail.value,
    });
    this.checkFormComplete();
  },

  onNameInput(e) {
    this.setData({
      'userInfo.name': e.detail.value,
    });
    this.checkFormComplete();
  },

  onPhoneInput(e) {
    this.setData({
      'userInfo.phone': e.detail.value,
    });
    this.checkFormComplete();
  },

  checkFormComplete() {
    const { name, phone, address } = this.data.userInfo;
    const isFormComplete =
      name &&
      phone &&
      address.length === 3 &&
      !address.includes('省份') &&
      !address.includes('城市') &&
      !address.includes('区');
    this.setData({
      isFormComplete,
    });
  },

  purchaseForm(data) {
    const { personName, phoneNum } = data.detail.value;
    const region = this.data.region;
    if (
      !personName ||
      !phoneNum ||
      region.includes('省') ||
      region.includes('市') ||
      region.includes('区')
    ) {
      wx.showToast({
        title: '请完整填写所有字段',
        icon: 'none',
        duration: 1500,
      });
      return;
    }
    this.setData({
      'userInfo.name': personName,
      'userInfo.phone': phoneNum,
      'userInfo.address': this.data.userInfo.address.join(' '),
    });
    console.log(this.data.userInfo);
    wx.request({
      url: 'http://1.94.51.11:8850/user/buySu7',
      method: 'POST',
      header: {
        Cookie: wx.getStorageSync('session'),
      },
      data: {
        ...this.data.userInfo,
      },
      success: res => {
        if (res.data.msg === 'success') {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000,
          });
          wx.reLaunch({
            url: '/pages/index/index',
          });
        } else {
          wx.showToast({
            title: '提交失败',
            icon: 'none',
          });
        }
      },
      fail: error => {
        console.error('请求失败:', error);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none',
        });
      },
    });
  },
});
